﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using C.Unite;
using C.Entities;
using ChanExt;
using MySoft.Data;
using System.Text;
using LitJson;

namespace ArtLand.OA.Project.Project
{
    public partial class Pro_ContatList : CommonPageBase
    {

        /// <summary>
        /// 取得权限
        /// </summary>
        /// <returns></returns>
        public bool GetQX()
        {

            bool n = true;
            string UserKeys = UserPower.GetHaveKey();
            if (!UserKeys.Contains("View"))
            {
                PageContext.RegisterStartupScript("alert('您未有查看权限！');RemTab('dynamic_added_tab_tab_" + UserPower.GetKeyWord() + "');");
                n = false;
            }
            else
            {
                //if (CookInfo.EAdminTrueName().Trim() == "陈爱国")
                //{
                //    Button1.Hidden = false;
                //}
                if (!UserKeys.Contains("Add"))
                {
                    btnNew.Hidden = true;
                }

                if (!UserKeys.Contains("Del"))
                {
                    Button2.Hidden = true;
                }
                if (!UserKeys.Contains("Edit"))
                {
                    Button1.Hidden = true;
                }
                if (!UserKeys.Contains("Operation"))
                {
                    Grid1.Columns[Grid1.Columns.Count - 1].Hidden = true;
                }
            }
            return n;
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //if (GetQX())
               // {
                    btnNew.OnClientClick = Window1.GetShowReference("Pro_ContatChange.aspx", "添加新合同");
                    BindGrid(GetWhere());

                    decimal d = TbsDbSession.Default.From<Proj_Contat>().Select(Proj_Contat._.AMOUNT.Sum()).ToScalar<decimal>();
                    decimal p = TbsDbSession.Default.FromSql("select sum(PAMOUT) from Proj_Rement a,Proj_Contat b where a.CONNUB=b.CONNUB").ToScalar<decimal>(); //TbsDbSession.Default.From<Proj_Popayf>().Select(Proj_Popayf._.REMOUT.Sum()).ToScalar<decimal>();

                    ToolbarText2.Text = "<b>合同未收金额:<font color='red'>" + (d - p).ToString() + "</font></b>";
               // }
            }
        }


        #region BindGrid
        private void BindGrid(WhereClip wc)
        {
            Grid1.RecordCount = TbsDbSession.Default.From<Proj_Contat>().Where(wc).Count();

            List<Proj_Contat> items = TbsDbSession.Default.From<Proj_Contat>().Where(wc).OrderBy(Proj_Contat._.ID.Desc).Page(Grid1.PageSize, (Grid1.PageIndex + 1)).ToList();

            // 3.绑定到Grid
            Grid1.DataSource = items;
            Grid1.DataBind();
        }



        protected void Grid1_PageIndexChange(object sender, ChanExt.GridPageEventArgs e)
        {
            Grid1.PageIndex = e.NewPageIndex;
            BindGrid(GetWhere());
        }

        public WhereClip GetWhere()
        {
            WhereClip wc = WhereClip.All;

            if (!string.IsNullOrEmpty(Request["pid"]))
            {
                Proj_Main pm = TbsDbSession.Default.From<Proj_Main>().Where(Proj_Main._.ID == int.Parse(Request["pid"])).ToFirst();
                wc = wc && Proj_Contat._.PRJNUB == pm.PRJNUB;
            }
            if (!String.IsNullOrEmpty(ttbxMyBox2.Text))
            {
                wc = wc && (Proj_Contat._.CONNUB.Contain(ttbxMyBox2.Text) || Proj_Contat._.CONDES.Contain(ttbxMyBox2.Text) || Proj_Contat._.CUTNUB.Contain(ttbxMyBox2.Text));
            }
            if (!string.IsNullOrEmpty(Request["t"]))
            {

                List<VI_C2> listc = TbsDbSession.Default.From<VI_C2>().Where(VI_C2._.C == 0).ToList();
                int[] listint = (from p in listc select p.ID).ToArray();
                if (listint.Length > 0)
                    wc = wc && Proj_Contat._.ID.SelectIn<int>(listint);
                else
                {
                    PageContext.RegisterStartupScript("top.__doPostBack('hid_btn', '');top.RemoveT('M_noordercon_x');");
                }
            }
            if (!string.IsNullOrEmpty(Request["s"]))
            {
                List<VI_C5> listc = TbsDbSession.Default.From<VI_C5>().Where(VI_C5._.C == 1).ToList();
                int[] listint = (from p in listc select p.ID).ToArray();
                if (listint.Length > 0)
                    wc = wc && Proj_Contat._.ID.SelectIn<int>(listint);
                else
                {
                    PageContext.RegisterStartupScript("top.__doPostBack('hid_btn', '');top.RemoveT('M_waitsong_x');");
                }
            }

            return wc;
        }
        // 点击 TwinTriggerBox 的搜索按钮
        protected void ttbxMyBox2_Trigger2Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(ttbxMyBox2.Text))
            {
                // 执行搜索动作
                BindGrid(GetWhere());
                ttbxMyBox2.ShowTrigger1 = true;
            }
            else
            {
                Alert.ShowInTop("请输入你要搜索的关键词！");
            }
        }

        // 点击 TwinTriggerBox 的取消按钮
        protected void ttbxMyBox2_Trigger1Click(object sender, EventArgs e)
        {
            // 执行清空动作

            ttbxMyBox2.Text = "";
            ttbxMyBox2.ShowTrigger1 = false;
            BindGrid(GetWhere());
        }
        #endregion

        protected void Grid1_RowDataBound(object sender, GridRowEventArgs e)
        {
            string id = e.Values[6].ToString();
            decimal dc = 0;
            decimal z = decimal.Parse(e.Values[5].ToString());
            string conno = e.Values[0].ToString();
            List<Proj_Rement> rementList = TbsDbSession.Default.From<Proj_Rement>().Where(Proj_Rement._.CONNUB == conno).ToList();
            foreach (Proj_Rement item in rementList)
            {
                dc += item.PAMOUT.Value;
            }
            decimal y = z - dc;
            e.Values[6] = "<a href=\"javascript:;\" onclick=\"TabView('/Project/Pro_RementList.aspx?cid=" + id + "', 'tab_wxaddasdf', '查看收款记录', '');\">" + y.ToString() + "</a>";

            //string color = e.Values[7].ToString();
            //string bold = e.Values[8].ToString();
            //if (bold == "True")
            //    bold = "bold";
            //else
            //    bold = "";
            //string title = "<span style=\"color:{0};font-weight:{1}\">" + e.Values[0] + "</span>";
            //title = string.Format(title, color, bold);
            //e.Values[0] = title;
            //e.Values[7] = "<a href=\"javascript:;\" onclick=\"TabView('/AfterSale/ASale_RePairChange.aspx?id=" + e.Values[7] + "', 'tab_wxadd', '修改维修记录', '/icon/comment_edit.png');\"><img src=\"/icon/comment_edit.png\" /></a>";
        }

        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            int id = int.Parse(Grid1.DataKeys[e.RowIndex][0].ToString());
            if (e.CommandName == "Del")
            {
                Proj_Contat pcon = new Proj_Contat();
                pcon.ID = id;
                pcon.Attach();
                pcon.IsDel = true;

                TbsDbSession.Default.Update<Proj_Contat>(pcon);
                Alert.ShowInTop("删除成功！");
                BindGrid(GetWhere());
            }
            if (e.CommandName == "CheckBox1")
            {
                CheckBoxField checkField = (CheckBoxField)Grid1.FindColumn(e.ColumnIndex);
                bool checkState = checkField.GetCheckedState(e.RowIndex);
                Proj_Contat tea = new Proj_Contat();
                tea.ID = id;
                tea.Attach();
                tea.IsFinsh = checkState;
                TbsDbSession.Default.Update<Proj_Contat>(tea);
                PageContext.RegisterStartupScript("top.__doPostBack('hid_btn', '');");
                BindGrid(GetWhere());
            }
        }

        protected void Grid1_RowDoubleClick(object sender, GridRowClickEventArgs e)
        {
            int id = int.Parse(Grid1.DataKeys[e.RowIndex][0].ToString());
            string isfinsh = Grid1.DataKeys[e.RowIndex][1].ToString();
            if (isfinsh == "False")
                PageContext.RegisterStartupScript(Window1.GetShowReference("Pro_ContatChange.aspx?id=" + id, "修改"));
        }

        protected void Button1_Click(object sender, EventArgs e)
        {

            string isfinsh = FormInfo.GetGridSelected(Grid1, 1);
            if (isfinsh == "False")
                FormInfo.GridEdit(Grid1, Window1, "Pro_ContatChange.aspx");

        }

        protected void Button2_Click(object sender, EventArgs e)
        {
            FormInfo.GridDelete<Proj_Contat>(Grid1, Window1, new Proj_Contat());
            BindGrid(GetWhere());
        }

        protected void btnMoneyView_Click(object sender, EventArgs e)
        {
            FormInfo.GridView(Grid1, "/Project/Pro_RementList.aspx", "cid", "/icon/application-list.png", "查看该合同收款记录");
        }

        protected void btnMoneyAdd_Click(object sender, EventArgs e)
        {
            WindowAttribute wa = new WindowAttribute();
            wa.Title = "添加收款记录";
            FormInfo.GridEdit(Grid1, Window1, "Pro_RementChange.aspx", wa, "cid");
        }

        protected void btnPoDataAdd_Click(object sender, EventArgs e)
        {
            WindowAttribute wa = new WindowAttribute();
            wa.Title = "新增采购订单";
            FormInfo.GridEdit(Grid1, Window1, "Pro_PoDataChange.aspx", wa, "cid");
        }

        protected void Grid1_RowSelect(object sender, GridRowSelectEventArgs e)
        {
            if (Grid1.SelectedRowIndexArray.Length > 1)
            {
                Button1.Enabled = false;
                Button1.ToolTip = "只能选择一项进行修改";
            }
            else
            {
                string isfinsh = Grid1.DataKeys[e.RowIndex][1].ToString();
                if (isfinsh == "True")
                {
                    Button1.Enabled = false;
                    Button1.ToolTip = "送货已完成，无法修改！";
                }
                else
                    Button1.Enabled = true;
            }
        }

        protected void MenuButton1_Click(object sender, EventArgs e)
        {
            WindowAttribute wa = new WindowAttribute();
            wa.Title = "新增运货计划";
            FormInfo.GridEdit(Grid1, Window2, "Pro_DeliveryChange.aspx", wa, "cid");
        }

        protected void btnPoDataView_Click(object sender, EventArgs e)
        {
            FormInfo.GridView(Grid1, "/Project/Pro_PoDataList.aspx", "cid", "/icon/application-task.png", "查看采购记录");
        }

        protected void MenuButton2_Click(object sender, EventArgs e)
        {
            FormInfo.GridView(Grid1, "/Project/Pro_DeliveryList.aspx", "cid", "/icon/lorry_go.png", "查看送货计划记录");
        }

        protected void btnView_Click(object sender, EventArgs e)
        {
            WindowAttribute wa = new WindowAttribute();
            wa.Title = "查看";
            FormInfo.GridEdit(Grid1, Window1, "Pro_ContatChange.aspx?p=1", wa, "");
        }

        protected void btnFind_Click(object sender, EventArgs e)
        {
            PageContext.RegisterStartupScript(Window3.GetShowReference());
            //   FormInfo.ShowTab("/Project/Pro_ContatReport.aspx", "findt", "", "合同报表查询");
        }

        protected void btn_find_Click(object sender, EventArgs e)
        {
            string cno = txt_CUTNUB.Text;
            string stime = txt_StartTime.Text;
            string etime = txt_EndTime.Text;


            FormInfo.ShowTab("/Project/Pro_ContatReport.aspx?cno=" + cno + "&stime=" + stime + "&etime=" + etime, "findt", "", "合同报表查询");
        }
    }
}